const mysql = require('mysql2/promise');
const log = require('../utils/log')

class Db {
    constructor(config) {
        this.connection = null;
        this.config = config;

    }

    async connect() {
        // this.connection = await mysql.createConnection(this.config);
        this.connection = await mysql.createPool(this.config);
        log.error('数据库连接成功！');
    }

    async query(sql, values) {
        if (!this.connection) {
            throw new Error('数据库未连接！');
        }
        const [rows, fields] = await this.connection.execute(sql, values);
        return rows;
    }

    async close() {
        if (this.connection) {
            await this.connection.end();
            log.error('数据库连接已关闭！');
        }
    }
}

module.exports = Db;